package com.spzx.common.rabbit.service;


import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 发送消息
     *
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param message    消息
     */

    public Boolean sendMessage(String exchange, String routingKey, Object message){

        //根据id在redis中查询消息副本
        String id = UUID.randomUUID().toString().replace("-", "");

        GuiguCorrelationData guiguCorrelationData = new GuiguCorrelationData();
        guiguCorrelationData.setMessage(message);
        guiguCorrelationData.setExchange(exchange);
        guiguCorrelationData.setRoutingKey(routingKey);
        guiguCorrelationData.setId(id);
        //将消息副本存储在redis中
        redisTemplate.opsForValue().set(id,guiguCorrelationData, 5, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend(exchange, routingKey, message,guiguCorrelationData);
        return true;
    }


    public Boolean sendDelayMessage(String exchange, String routingKey, Object message){

        String id = UUID.randomUUID().toString().replace("-", "");

        GuiguCorrelationData guiguCorrelationData = new GuiguCorrelationData();
        guiguCorrelationData.setMessage(message);
        guiguCorrelationData.setExchange(exchange);
        guiguCorrelationData.setRoutingKey(routingKey);
        guiguCorrelationData.setId(id);
        guiguCorrelationData.setDelay(true);
        rabbitTemplate.convertAndSend(exchange, routingKey, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDelay(10000);
                return message;
            }
        }, guiguCorrelationData);
        return true;
    }
}
